from django import forms
from django.contrib.auth import get_user_model

from .models import Profile, Invitation

User = get_user_model()


class UserForm(forms.ModelForm):
    """用户基本信息表单"""
    email = forms.EmailField(label='邮箱')

    class Meta:
        model = User
        fields = ('email', 'username')

    def clean_username(self):
        """钩子函数，如果用户输入新的用户名且该用户名已经被别人使用则抛出异常，提醒用户"""
        username = self.cleaned_data.get('username')
        # self.instance获得当前的模型类对象
        if self.instance.username != username and User.objects.filter(username=username).exists():
            raise forms.ValidationError('该用户名已经被使用')
        return username

    def clean_email(self):
        """钩子函数，如果用户输入新的邮箱地址且该邮箱已经被别人使用则抛出异常，提醒用户"""
        email = self.cleaned_data.get('email')
        # self.instance获得当前的模型类对象
        if self.instance.email != email and User.objects.filter(email=email).exists():
            raise forms.ValidationError('该邮箱已经被使用')
        return email


class ProfileForm(forms.ModelForm):
    """用户额外信息"""
    class Meta:
        model = Profile
        fields = ('avatar',)


class InvitationForm(forms.ModelForm):
    """邀请表单"""
    class Meta:
        model = Invitation
        fields = ('name', 'email')